#include "MSSQLDb.h"

namespace SQLDoc
{
	const QString MSSQLDb::SELECT_TABLES_QUERY("select t.object_id, t.name, CAST(c.value AS VARCHAR(max)) from sys.tables t left outer join sys.extended_properties c on t.object_id = c.major_id and c.minor_id = 0");

	MSSQLDb::MSSQLDb(void)
		: DBDatabase()
	{ }

	MSSQLDb::~MSSQLDb(void)
	{ }

	void MSSQLDb::fillTables()
	{
		QSqlDatabase db = QSqlDatabase::database(reinterpret_cast<DBConnection*>(this->m_parentItem)->connectionName());
		ensureActive(db);

		QSqlQuery query(db);
		query.setForwardOnly(true);
		query.exec(SELECT_TABLES_QUERY);

		while (query.next())
		{
			MSSQLTable* t = new MSSQLTable();
			t->setId(query.value(0).toInt());
			t->setName(query.value(1).toString());
			t->setComment(query.value(2).toString());
			m_tables.append(t);
		}

		DBDatabase::fillTables();
	}

	void MSSQLDb::use(QSqlDatabase &db)
	{
		QSqlQuery query(db);
		query.exec(QString("use %1").arg(m_name));
		m_isActive = true;
	}
}
